import { createTree, ResTreeVO, TreeDataSource } from './entity';
import { Data } from 'ahooks/lib/usePagination/types';
import { request } from 'ice';

export interface QueryParams {
  /** 方法名 */
  name?: string;
  /** 接口路径 */
  code?: string;
  status?: number;
}

export interface ListVO {
  id?: number;
  /** 角色名称 */
  name?: string;
  /** 角色类型 */
  type?: number;
  /** 角色编码 */
  code?: string;
  /** 状态 */
  status?: number;
  createTime?: number;
}

export interface PData extends Data {
  list: ListVO[];
}

/** 列表 */
export const apiList = (pageParams: ICommon.PageParams, formData: QueryParams): Promise<PData> => {
  const params = {
    ...pageParams,
    ...formData,
  };
  return request.get<ICommon.Pagination<ListVO>>('/erp/role/list', { params }).then((res) => ({
    total: res?.total || 0,
    list: res?.data || [],
  }));
};

/**
 * 保存角色
 * @param params 角色信息
 * @returns
 */
export const saveRole = (params: ListVO): Promise<any> => {
  return request.post('/erp/role/save', { ...params });
};

/**
 * 删除角色
 * @param id
 * @returns
 */
export const deleteRole = (id?: number): Promise<any> => {
  return request.get('/erp/role/delete', { params: { id } });
};

/**
 * 获取资源树
 * @returns
 */
export const resTree = (): Promise<TreeDataSource[]> => {
  return request.get<ResTreeVO[]>('/erp/privilege/tree').then((res) => createTree(res));
};

/** 查询角色授权列表 */
export const queryRoleAuth = (roleId?: number): Promise<number[]> => {
  return request.get('/erp/role/privilege/list', { params: { roleId } });
};

export interface SaveRoleAuthParam {
  roleId: number;
  privilegeIds: number[];
}

/** 保存角色授权 */
export const saveRoleAuth = (params: SaveRoleAuthParam): Promise<any> => {
  return request.post('/erp/role/privilege/save', { ...params });
};
